'use strict';

import {
  userLogin, resetPassword,
  userRegister,
  findSu,
  updateSu,
  findUserByUsername,
  findUsers,
  updateUser,
  findUser,
  findUsersByPage,
  deleteUser,
  updatePassword
} from '../services/user';
import {setAuthority, setUser} from '../utils/authority';
import {reloadAuthorized} from '../utils/Authorized';
import {stringify} from 'qs';
import {routerRedux} from 'dva/router';
import {getPageQuery} from '../utils/utils';
import notify from '../components/NotificationExtra';

export default {
  namespace: 'user',
  state: {
    action: 'get',
    status: undefined,
    currentUser: {},
    registerResult: undefined,
  },

  effects: {
    * register({payload}, {call, put}) {
      const response = yield call(userRegister, payload);
      let result;
      if (response && response.status === 'ok') {
        result = 'success';
      } else {
        result = 'error';
      }
      yield put({
        type: 'onDataLoad',
        payload: {
          action: 'register',
          registerResult: result,
        },
      });
      return response;
    },
    * findSu({payload}, {call}) {
      const response = yield call(findSu, payload);
      return response;
    },
    * updateSu({payload}, {call}) {
      const response = yield call(updateSu, payload);
      return response;
    },
    * findUserByUsername({payload}, {call}) {
      const response = yield call(findUserByUsername, payload);
      return response;
    },
    * findUser({payload}, {call}) {
      const response = yield call(findUser, payload);
      return response;
    },
    * deleteUser({payload}, {call}) {
      const response = yield call(deleteUser, payload);
      return response;
    },
    * updateUser({payload}, {call}) {
      const response = yield call(updateUser, payload);
      return response;
    },
    * resetPassword({payload}, {call}) {
      const response = yield call(resetPassword, payload);
      return response;
    },
    * updatePassword({payload}, {call}) {
      const response = yield call(updatePassword, payload);
      return response;
    },
    * findUsersByPage({payload}, {call}) {
      const response = yield call(findUsersByPage, payload);
      return response;
    },
    * findUsers({payload}, {call, put}) {
      let {resultKey, table} = payload;
      let resKey = resultKey ? resultKey : table;
      delete payload['resultKey'];
      delete payload['table'];
      const response = yield call(findUsers, payload);
      if (response) {
        const payload = {};
        payload[resKey] = response.result;
        yield put({
          type: 'onDataLoad',
          payload,
        });
      }
      return response;
    },
    * login({payload}, {call, put}) {
      // todo 返回结果是{"status":"ok","type":"account","currentAuthority":"user"}
      // 实际可能没有currentAuthority这个字段，判断登录成功后，自己加上就行了
      const response = yield call(userLogin, payload);
      console.log('登录成功', response);
      const user = {username: payload.username};
      /**
       * 登录成功
       */
      if (response && response.status && response.status === 'ok') {
        const {result} = response;
        user.currentAuthority = result.userType;
        user.nickname = result.nickname;
        notify({message: '登录成功', type: 'info'});
        //message.success('登录成功');
        window.localStorage.setItem('loginInfo', JSON.stringify(result));

        yield put({
          type: 'changeLoginStatus',
          payload: {
            currentUser: user,
            action: 'login',
          },
        });
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let {redirect} = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
        return;
      }

      user.currentAuthority = 'guest';
      let msg = response && response.message ? response.message : '登录失败';
      notify({message: msg, type: 'error'});
      // message.error(msg);
      window.localStorage.clear();

      yield put(routerRedux.replace('/'));
    },
    /**
     * 免登录跳转
     * @param _
     * @param put
     * @returns {IterableIterator<*>}
     */* loginRout({payload}, {call, put}) {

      // const w=window.open('about:blank');
      // w.location.href=payload.url
      yield put(routerRedux.push(payload.url || '/'));
    },

    * logout(_, {put}) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
          currentUser: {},
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            // redirect: window.location.href,
          }),
        }),
      );
    },

  },

  reducers: {
    onDataLoad(state, {payload}) {
      return {...state, ...payload};
    },

    changeLoginStatus(state, {payload}) {
      setAuthority(payload.currentUser.currentAuthority || 'guest');
      setUser(JSON.stringify(payload.currentUser || {}));
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        currentUser: payload.currentUser,
      };
    },

  },
};

// function setStore(name, content) {
//   if (!name) return;
//   if (typeof content !== 'string') {
//     content = JSON.stringify(content);
//   }
//   window.localStorage.setItem(name, content);
// }
